/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年11月27日         Root.Lu
 */

package com.tianci.appstore.framework;

import com.tianci.appstore.utils.HandlerThread;

public abstract class Container {
    private ThreadGroup tg = null;
    private HandlerThread ht = null;
    private String name = null;

    private boolean bCreated = false, bDestroyed = false;

    public Container(String name) {
        this.name = name;
    }

    public synchronized final void create() {
        if (tg == null && ht == null) {
            tg = new ThreadGroup(name) {
                // @Override
                // public void uncaughtException(Thread t, Throwable e)
                // {
                // // TODO Auto-generated method stub
                // Container.this.uncaughtException(t, e);
                // }
            };
            tg.setMaxPriority(Thread.MIN_PRIORITY);
            ht = new HandlerThread(tg, "HandlerThread(" + name + ")");
            ht.start();
            postAction(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    onCreate();
                    bCreated = true;
                }
            });
        }
    }

    public synchronized final void destroy() {
        if (tg != null && ht != null) {
            postAction(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    onDestroy();
                    ht.shutdown();
                    ht = null;
                    tg = null;
                    bCreated = false;
                    bDestroyed = true;
                }
            });
        }
    }

    public final String getName()

    {
        return name;
    }

    public final boolean isCreated() {
        return bCreated;
    }

    public final boolean isDestroyed() {
        return bDestroyed;
    }

    protected final void postAction(Runnable run) {
        ht.postAction(run);
    }

    protected void uncaughtException(Thread t, Throwable e) {
        e.printStackTrace();
    }

    protected abstract void onCreate();

    protected abstract void onDestroy();
}
